﻿using System;
using Assets.Content.Scripts.DateBase;
using Sirenix.OdinInspector;
using Sirenix.Utilities;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Assets.Content.Scripts.UI.Start
{
    internal class LoadGamePanel : Widget.Widget
    {
        [SerializeField, LabelText("返回主界面按钮")]
        private Button _backMainMenuButton;

        [SerializeField, LabelText("载入游戏")]
        private Button[] _loadGame;

        [SerializeField, LabelText("删除游戏存档按钮")]
        private Button[] _deleteGameDate;

        protected override void Awake()
        {
            base.Awake();
            _backMainMenuButton.onClick.AddListener(OnClickBackButton);
            for (var i = 0; i < _loadGame.Length; i++)
            {
                var t = i;
                _loadGame[i].onClick.AddListener(() => OnClickLoadGame(t));
            }

            for (var i = 0; i < _deleteGameDate.Length; i++)
            {
                var t = i;
                _deleteGameDate[i].onClick.AddListener(() => DeleteGameDate(t));
            }
        }

        private void OnClickLoadGame(int index)
        {
            AccessPlayerDate.ID = index; // 记录当前选择的存档ID

            Hide();
            SceneManager.LoadScene("GameScene");
        }

        private void DeleteGameDate(int index)
        {
            var folder = AccessPlayerDate.GetFileFolder();
            folder[index].GetFileSystemInfos()[0].Delete();
            folder[index].Delete();

            for (var i = 0; i < 5; i++)
                transform.GetChild(1).GetChild(i).gameObject.SetActive(false);

            folder = AccessPlayerDate.GetFileFolder();
            for (var i = 0; i < folder.Length; i++)
            {
                transform.GetChild(1).GetChild(i).gameObject.SetActive(true);
                transform.GetChild(1).GetChild(i).GetChild(0).GetChild(0).GetComponent<Text>().text = folder[i].Name.Split('-')[1];
                transform.GetChild(1).GetChild(i).GetChild(1).GetChild(0).GetComponent<Text>().text = folder[i].GetFileSystemInfos()[0].LastWriteTime.ToLongTimeString();
            }
        }

        private void OnClickBackButton()
        {
            for (var i = 0; i < 5; i++)
                transform.GetChild(1).GetChild(i).gameObject.SetActive(false);

            StartManager.Instance.DisPlay(true);
            Hide();
        }
    }
}
